package cn.kailangtu.dataspot.update;

import android.content.Context;
import android.os.Environment;
import android.os.SystemClock;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.downloader.Error;
import com.downloader.OnCancelListener;
import com.downloader.OnDownloadListener;
import com.downloader.OnPauseListener;
import com.downloader.OnProgressListener;
import com.downloader.OnStartOrResumeListener;
import com.downloader.PRDownloader;
import com.downloader.Progress;

import java.io.File;

import cn.kailangtu.dataspot.AppBasicMethod;

public class Updater {

    public static String FILE_SYSTEM = "KLTFiles";
    private String TAG = "UPDATER==>";
    private Context mContext = null;

    private int status = 0;


    private static Updater instance = null;

    public static Updater getInstance(){
        if(instance == null)
        {
            instance = new Updater();
        }
        return instance;
    }

    /**
     * 下载过程
     */
    public synchronized void startDown(Context context, String url) {
        if(status == 0) {
            status = 1;
            mContext = context;
            String path = getApksDir(context);

            String name = DateUtil.get获取格式化时间_天() + ".apk";
            Log.d(TAG,"URL:"+url);
            Log.d(TAG,"PATH:"+path);
            Log.d(TAG,"NAME:"+name);
            PRDownloader.download(url, path, name)
                    .build()
                    .setOnStartOrResumeListener(new OnStartOrResumeListener() {
                        @Override
                        public void onStartOrResume() {
                            Log.d(TAG, "开始下载");
                            status = 2;
                        }
                    })
                    .setOnPauseListener(new OnPauseListener() {
                        @Override
                        public void onPause() {
                            Log.d(TAG, "暂停下载");
                            status = 3;
                        }
                    })
                    .setOnCancelListener(new OnCancelListener() {
                        @Override
                        public void onCancel() {
                            Log.d(TAG, "取消下载");
                            status = 0;
                        }
                    })
                    .setOnProgressListener(new OnProgressListener() {
                        @Override
                        public void onProgress(Progress progress) {
                            long currentBytes = progress.currentBytes;
                            long totalBytes = progress.totalBytes;
                            String strCurrent = Formatter.formatFileSize(mContext, currentBytes);
                            String strTotal = Formatter.formatFileSize(mContext, totalBytes);
                            Log.d(TAG, "下载中：" + strCurrent + "  总大小：" + strTotal);
                        }
                    })
                    .start(new OnDownloadListener() {
                        @Override
                        public void onDownloadComplete() {
                            Log.d(TAG, "APK下载完成");
                            status = 4;
                            //CabinetApplication.getSystemTools().installApp(path + "/" + name);
                           // AppManagerUtils.InstanllApp(path + "/" + name, AppBasicMethod.getInstance().getContext().getPackageName());
                           // AppManagerUtils.silentInstall(AppBasicMethod.getInstance().getContext(),path + "/" + name ,AppBasicMethod.getInstance().getContext().getPackageName());
                            AppManagerUtils.openAppInstanll();
                            status = 5;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    SystemClock.sleep(60000);
                                    status = 0;
                                }
                            }).start();
                        }

                        @Override
                        public void onError(Error error) {
                            Log.d(TAG, "APK下载失败！"+ JSONObject.toJSONString(error));
                            status = 0;
                        }
                    });
        }
    }

    public String getSmBoxDir(Context context) {
        String cachePath = getSystemDir(context) + File.separator
                + FILE_SYSTEM;
        createOrExistsDir(cachePath);
        return cachePath;
    }

    public String getApksDir(Context context) {
        String cachePath = getSystemDir(context) + File.separator
                + FILE_SYSTEM+File.separator
                + "apks";
        createOrExistsDir(cachePath);
        return cachePath;
    }

    public String getSystemDir(Context context) {
        String cachePath = context.getCacheDir().getPath();
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {// 优先保存到SD卡中
            cachePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {// 如果SD卡不存在，就保存到本应用的目录下
            cachePath = context.getExternalFilesDir(FILE_SYSTEM).getAbsolutePath();
        }
        return cachePath;
    }

    /**
     * 判断目录是否存在，不存在则判断是否创建成功
     *
     * @param file 文件
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsDir(final File file) {
        // 如果存在，是目录则返回true，是文件则返回false，不存在则返回是否创建成功
        return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
    }

    /**
     * 判断目录是否存在，不存在则判断是否创建成功
     *
     * @param dirPath 目录路径
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsDir(final String dirPath) {
        return createOrExistsDir(getFileByPath(dirPath));
    }

    /**
     * 根据文件路径获取文件
     *
     * @param filePath 文件路径
     * @return 文件
     */
    public static File getFileByPath(final String filePath) {
        return isSpace(filePath) ? null : new File(filePath);
    }

    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}
